package com.yx.service.init;

import com.yx.entity.SysRole;
import com.yx.entity.SysUser;
import com.yx.entity.SysUserRole;
import com.yx.mapper.SysRoleMapper;
import com.yx.mapper.SysUserMapper;
import com.yx.mapper.SysUserRoleMapper;
import com.yx.sys.SysConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Description: <br/>
 * 初始化admin用户和角色
 * <p>
 * <br/>
 * @Auther: zhangqi
 * @create 2019/11/7 14:31
 */
@Component
public class InitSysUser {


    /**
     * 系统用户
     */
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 系统用户角色
     */
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 系统角色
     */
    @Autowired
    private SysRoleMapper sysRoleMapper;

    public void init() {
        // 查询角色
        SysRole role = sysRoleMapper.getInfo(SysConst.SYS_ROLE);

        // 初始化角色
        if (Objects.isNull(role)) {
            SysRole sysRole = new SysRole();
            sysRole.setRoleId(SysConst.SYS_ROLE);
            sysRole.setRoleName(SysConst.SYS_ROLE_NAME);
            sysRoleMapper.insert(sysRole);
        }

        // 初始化用户
        SysUser user = sysUserMapper.getUserByUserName(SysConst.SYS_LOGIN_NAME);
        if (Objects.isNull(user)) {
            user = new SysUser();
            // 设置初始密码
            user.setPassword(SysConst.SYS_DEFAULT_PASSWORD);
            // 设置登录名
            user.setUserName(SysConst.SYS_LOGIN_NAME);
            user.setCreateBy("0");
            user.setUpdateBy("0");
            // 设置昵称
            user.setNickName(SysConst.SYS_ROLE_NAME);
            sysUserMapper.insert(user);
        }
        SysUser sysUser = sysUserMapper.getUserByUserName(SysConst.SYS_LOGIN_NAME);
        // 定义查询条件
        SysUserRole userRole = sysUserRoleMapper.getInfoByPrimaryKey(SysConst.SYS_ROLE, sysUser.getUserId());
        // 初始化用户角色
        if (Objects.isNull(userRole)) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(SysConst.SYS_ROLE);
            sysUserRole.setUserId(user.getUserId());
            sysUserRoleMapper.insert(sysUserRole);
        }

    }

}
